import * as FileSystem from "expo-file-system";

import { Audio, Video } from "expo-av";
import {
  Button,
  FlatList,
  PermissionsAndroid,
  Platform,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import React, { useEffect, useState } from "react";

import DateTimePicker from "@react-native-community/datetimepicker";
import Dialog from "react-native-dialog";

export default function TabTwoScreen() {
  const [mediaFiles, setMediaFiles] = useState([]);
  const [filteredFiles, setFilteredFiles] = useState([]);
  const [playingUri, setPlayingUri] = useState(null);
  const [sound, setSound] = useState(null);
  const [videoUri, setVideoUri] = useState(null);
  const [showDialog, setShowDialog] = useState(false);
  const [currentFileUri, setCurrentFileUri] = useState(null);
  const [newFileName, setNewFileName] = useState("");
  const [selectedDate, setSelectedDate] = useState(new Date());
  const [datePickerVisible, setDatePickerVisible] = useState(false);

  useEffect(() => {
    const readMediaFiles = async () => {
      if (Platform.OS === "android") {
        const granted = await requestStoragePermission();
        if (!granted) {
          console.log("Storage permission denied");
          return;
        }
      }

      const dirUri = `${FileSystem.documentDirectory}`;
      try {
        const files = await FileSystem.readDirectoryAsync(dirUri);
        const filteredFiles = files.filter(
          (file) => file.endsWith(".mp4") || file.endsWith(".3gp")
        );
        const mediaFiles = await Promise.all(
          filteredFiles.map(async (file) => {
            const fileUri = `${dirUri}${file}`;
            const info = await FileSystem.getInfoAsync(fileUri);
            return { uri: fileUri, ...info };
          })
        );
        setMediaFiles(mediaFiles);
        setFilteredFiles(mediaFiles); // 初始化时展示所有文件
      } catch (error) {
        console.error("Error reading media files: ", error);
      }
    };

    readMediaFiles();
  }, [selectedDate]);

  useEffect(() => {
    // 根据 selectedDate 过滤文件
    const filtered = mediaFiles.filter((file) => {
      const fileDate = new Date(file.modificationTime);
      const formattedDate = fileDate.toISOString().split("T")[0]; // yyyy-mm-dd
      return formattedDate === selectedDate.toISOString().split("T")[0];
    });
    // TODO:注意：这里过滤出来，没有一个事件，就默认不适用了，展示所有
    filtered.length && setFilteredFiles(filtered);
    alert(JSON.stringify(filtered));
  }, [selectedDate, mediaFiles]);

  const getAllRadios = async () => {};

  const requestStoragePermission = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
        {
          title: "Storage Permission Required",
          message: "This app needs access to your storage to play media files",
          buttonNeutral: "Ask Me Later",
          buttonNegative: "Cancel",
          buttonPositive: "OK",
        }
      );
      return granted === PermissionsAndroid.RESULTS.GRANTED;
    } catch (err) {
      console.warn(err);
      return false;
    }
  };

  const playRecording = async (uri) => {
    if (uri.endsWith(".mp4")) {
      setVideoUri(uri);
      return;
    }

    if (sound) {
      await sound.unloadAsync();
      setSound(null);
    }

    try {
      const soundUri = uri.startsWith("file://") ? uri : `file://${uri}`;
      const { sound: newSound } = await Audio.Sound.createAsync({
        uri: soundUri,
      });
      setSound(newSound);
      setPlayingUri(uri);
      await newSound.playAsync();
      newSound.setOnPlaybackStatusUpdate((status) => {
        if (status.didJustFinish) {
          setPlayingUri(null);
          newSound.unloadAsync();
          setSound(null);
        }
      });
    } catch (error) {
      console.error("Error playing audio file: ", error);
    }
  };

  const stopPlayback = async () => {
    if (sound) {
      await sound.stopAsync();
      await sound.unloadAsync();
      setSound(null);
      setPlayingUri(null);
    }
    setVideoUri(null);
  };

  const renameFile = (oldUri) => {
    setCurrentFileUri(oldUri);
    setNewFileName(oldUri.split("/").pop()); // 默认文件名
    setShowDialog(true);
  };

  const handleRename = async () => {
    if (newFileName) {
      const newUri =
        currentFileUri.substring(0, currentFileUri.lastIndexOf("/") + 1) +
        newFileName;
      try {
        await FileSystem.moveAsync({
          from: currentFileUri,
          to: newUri,
        });
        setMediaFiles((prevFiles) =>
          prevFiles.map((file) =>
            file.uri === currentFileUri ? { ...file, uri: newUri } : file
          )
        );
        setFilteredFiles((prevFiles) =>
          prevFiles.map((file) =>
            file.uri === currentFileUri ? { ...file, uri: newUri } : file
          )
        );
        setShowDialog(false);
      } catch (error) {
        console.error("Error renaming file: ", error);
      }
    }
  };

  const handleDateChange = (event, selectedDate) => {
    setDatePickerVisible(false);
    if (selectedDate) {
      setSelectedDate(selectedDate);
    }
  };

  const renderMediaFile = ({ item }) => (
    <View style={styles.mediaFileContainer}>
      <Text style={styles.mediaFile}>{item.uri.split("/").pop()}</Text>
      <TouchableOpacity
        style={styles.playButton}
        onPress={() => playRecording(item.uri)}
        disabled={playingUri === item.uri || videoUri === item.uri}
      >
        <Text style={styles.playButtonText}>
          {playingUri === item.uri || videoUri === item.uri
            ? "Playing"
            : "Play"}
        </Text>
      </TouchableOpacity>
      <TouchableOpacity style={styles.stopButton} onPress={stopPlayback}>
        <Text style={styles.stopButtonText}>Stop</Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={styles.renameButton}
        onPress={() => renameFile(item.uri)}
      >
        <Text style={styles.renameButtonText}>Rename</Text>
      </TouchableOpacity>
    </View>
  );

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Tab读取公开目录的音频展示和播放</Text>
      <Button title="获取所有日期" onPress={getAllRadios} />
      <TouchableOpacity
        style={styles.dateButton}
        onPress={() => setDatePickerVisible(true)}
      >
        <Text style={styles.dateButtonText}>选择日期</Text>
      </TouchableOpacity>
      {datePickerVisible && (
        <DateTimePicker
          value={selectedDate}
          mode="date"
          display="default"
          onChange={handleDateChange}
        />
      )}
      <Text style={styles.dateButtonBlackText}>
        日期:{JSON.stringify(selectedDate)}
      </Text>
      <FlatList
        data={filteredFiles}
        keyExtractor={(item, index) => index.toString()}
        renderItem={renderMediaFile}
        style={styles.list}
      />
      {videoUri && (
        <Video
          source={{ uri: videoUri }}
          rate={1.0}
          volume={1.0}
          isMuted={false}
          resizeMode="contain"
          shouldPlay
          style={styles.video}
        />
      )}
      {/* Rename Dialog */}
      <Dialog.Container visible={showDialog}>
        <Dialog.Title>Rename File</Dialog.Title>
        <Dialog.Input
          value={newFileName}
          onChangeText={setNewFileName}
          placeholder="Enter new file name"
        />
        <Dialog.Button label="Cancel" onPress={() => setShowDialog(false)} />
        <Dialog.Button label="Rename" onPress={handleRename} />
      </Dialog.Container>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "flex-start",
    paddingTop: 20,
  },
  title: {
    fontSize: 20,
    fontWeight: "bold",
    marginBottom: 20,
  },
  dateButton: {
    backgroundColor: "#007BFF",
    padding: 10,
    borderRadius: 5,
    marginBottom: 20,
  },
  dateButtonText: {
    color: "#fff",
    fontSize: 16,
  },
  dateButtonBlackText: {
    // color: "#fff",
    fontSize: 16,
  },
  list: {
    width: "100%",
    paddingHorizontal: 20,
  },
  mediaFileContainer: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 10,
    paddingHorizontal: 10,
    paddingVertical: 10,
    borderColor: "#ccc",
    borderWidth: 1,
    borderRadius: 5,
    backgroundColor: "#f9f9f9",
  },
  mediaFile: {
    fontSize: 16,
    flex: 1,
  },
  playButton: {
    backgroundColor: "#007BFF",
    padding: 10,
    borderRadius: 5,
    marginLeft: 10,
  },
  playButtonText: {
    color: "#fff",
    fontSize: 14,
  },
  stopButton: {
    backgroundColor: "#FF6347",
    padding: 10,
    borderRadius: 5,
    marginLeft: 10,
  },
  stopButtonText: {
    color: "#fff",
    fontSize: 14,
  },
  renameButton: {
    backgroundColor: "#FFA500",
    padding: 10,
    borderRadius: 5,
    marginLeft: 10,
  },
  renameButtonText: {
    color: "#fff",
    fontSize: 14,
  },
  video: {
    width: "100%",
    height: 200,
    marginTop: 20,
  },
});
